<?php

include_once 'Eraser/Eraser.php';

const MAX_TEMP = 86400 * 30;

$eraser = new Eraser();

$option = $eraser->get('o', 'Param Error');
$uid = $eraser->get('u', 'Unique Label Error');

$eraser->setUid($uid);

if ($option == 'init') {
    $data = $eraser->init();
    echo $eraser->out([1, 'success', $data]);
} elseif ($option == 'search') {
    $platform = $eraser->get('p', 'Library Not Specific');
    $keyword = $eraser->get('k', 'Param Error');

    $res = $eraser->search($platform, $keyword);

    $ret = [];
    foreach ($res as $key => $item) {
        $album = $eraser->get_album($platform, $item['pic_id']);
        if ($key == 0) {
            $author = implode(', ', $item['artist']);
            $data = $eraser->get_data($platform, $item['url_id'], $item['lyric_id'], $album, $item['name'], $author, $item['id']);
            array_push($ret, [
                'id' => $item['id'],
                'name' => $item['name'],
                'author' => $author,
                'album' => $album,
                'url_id' => $item['url_id'],
                'url' => $data['url'],
                'lyric_id' => $item['lyric_id'],
                'lyric' => $data['lyric'],
                'platform' => $platform,
                'load_at' => Eraser::$now
            ]);
        } else {
            array_push($ret, [
                'id' => $item['id'],
                'name' => $item['name'],
                'author' => implode(', ', $item['artist']),
                'album' => $album,
                'url_id' => $item['url_id'],
                'url' => $item['url_id'],
                'lyric_id' => $item['lyric_id'],
                'lyric' => $item['lyric_id'],
                'platform' => $platform,
                'load_at' => 0
            ]);
        }
    }

    // temp playlist, so next time open it immediately
    $eraser->save_list($ret);

    echo $eraser->out([1, 'success', $ret]);
} elseif ($option == 'parse') {
    $platform = $eraser->get('p', 'Library Not Specific');
    $name = $eraser->get('n', 'Param Error');
    $author = $eraser->get('t', 'Param Error');
    $url_id = $eraser->get('r', 'Param Error');
    $lyric_id = $eraser->get('l', 'Param Error');
    $album = $eraser->get('a', 'Param Error', false);
    $song_id = $eraser->get('s', 'Param Error');

    $data = $eraser->get_data($platform, $url_id, $lyric_id, $album, $name, $author, $song_id);

    $ret = [
        'url' => $data['url'],
        'lyric' => $data['lyric'],
        'load_at' => Eraser::$now
    ];

    echo $eraser->out([1, 'success', $ret]);
} elseif ($option == 'wipe') {
    $key = $eraser->get('k', 'Key Not Specific');

    $s = ['history_search', 'history_play'];
    if (!in_array($key, $s)) {
        echo $eraser->out([0, 'Key Error']);
        exit();
    }

    $eraser->wipe($key);

    echo $eraser->out([1, 'success']);
}
